package com.hfy.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hfy.model.dto.user.FollowDto;
import com.hfy.model.po.user.FollowPo;
import com.hfy.user.mapper.FollowMapper;
import com.hfy.user.service.FollowService;
import org.springframework.stereotype.Service;
import result.Result;
import utils.CheckUtils;

/**
 * @ author 韩
 * time: 2024/10/29 20:33
 */

@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, FollowPo> implements FollowService {

    @Override
    public Result follow(FollowDto dto) {
        Boolean doFollow = dto.getDoFollow();
        String idolAccount = dto.getIdolAccount();
        String fansAccount = dto.getFansAccount();
        if (!CheckUtils.theStringIsLong(fansAccount)) {
            return Result.error("你知道的账号是一串数字");
        }
        if (!CheckUtils.theStringIsLong(idolAccount)) {
            return Result.error("你知道的账号是一串数字");
        }

        if (doFollow) {
            // 检查是否已存在关注记录
            LambdaQueryWrapper<FollowPo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(FollowPo::getFansAccount, fansAccount)
                    .eq(FollowPo::getIdolAccount, idolAccount);
            FollowPo existingFollow = getOne(queryWrapper);
            if (existingFollow != null) {
                // 已存在记录，设置 isDie 为 false
                existingFollow.setIsDie(0);
                updateById(existingFollow);
            } else {
                // 不存在记录，新建关注记录
                FollowPo followPo = new FollowPo();
                followPo.setFansAccount(fansAccount);
                followPo.setIdolAccount(idolAccount);
                followPo.setIsDie(0);
                save(followPo);
            }
            return Result.ok("关注成功！");
        } else {
            // 进行取消关注操作
            LambdaUpdateWrapper<FollowPo> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(FollowPo::getIsDie, 1).eq(FollowPo::getFansAccount, fansAccount)
                    .eq(FollowPo::getIdolAccount, idolAccount);
            update(updateWrapper);
            return Result.ok("取消关注成功！");
        }

    }

}
